<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="城市名称" prop="cityName">
        <el-input
          v-model="queryParams.cityName"
          placeholder="请输入"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!--<el-form-item label="父级城市id" prop="parentCityId">-->
      <!--<el-input-->
      <!--v-model="queryParams.parentCityId"-->
      <!--placeholder="请输入"-->
      <!--clearable-->
      <!--size="small"-->
      <!--@keyup.enter.native="handleQuery"-->
      <!--/>-->
      <!--</el-form-item>-->
      <!--<el-form-item label="级别后台维护" prop="level">-->
      <!--<el-input-->
      <!--v-model="queryParams.level"-->
      <!--placeholder="请输入"-->
      <!--clearable-->
      <!--size="small"-->
      <!--@keyup.enter.native="handleQuery"-->
      <!--/>-->
      <!--</el-form-item>-->
      <!--<el-form-item label="状态" prop="status">-->
      <!--<el-select v-model="queryParams.status" placeholder="请选择" clearable size="small">-->
      <!--<el-option label="请选择字典生成" value="" />-->
      <!--</el-select>-->
      <!--</el-form-item>-->
      <el-form-item label="状态">
        <el-select v-model="queryParams.status" placeholder="选择状态" clearable size="small" prop="status">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:city:add']"
        >新增</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">

      </el-col>

    </el-row>

    <el-table
      v-loading="loading"
              :data="cityList"
              @selection-change="handleSelectionChange"
      row-key="cityId"

      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column type="selection" width="55" align="center" />
      <!--<el-table-column label="" align="center" prop="cityId" />-->
      <el-table-column label="省份城市" align="center" prop="cityName" />
      <!--<el-table-column label="城市名称" align="center" prop="cityName" />-->
      <!--<el-table-column label="" align="center" prop="parentCityId" />-->
      <!--<el-table-column label="" align="center" prop="level" />-->
      <el-table-column label="状态" align="center" prop="status":formatter="statusFormat" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if ="!scope.row.parentCityId"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleAdd1(scope.row)"
            v-hasPermi="['system:city:edit']"
          >添加城市</el-button>
          <el-button
            v-if ="scope.row.parentCityId"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:city:edit']"
          >修改</el-button>
          <el-button
            v-if ="scope.row.parentCityId"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:city:remove']"
          >删除</el-button>
          <el-button
            v-if ="scope.row.parentCityId"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleGet(scope.row)"
            v-hasPermi="['system:city:guan']"
          >关联服务</el-button>

        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改城市对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!--<el-form-item label="城市名称" prop="cityName">-->
          <!--<el-cascader-->
            <!--size="large"-->
            <!--:options="options"-->
            <!--v-model="selectCity"-->
            <!--@change="handleChange">-->
          <!--</el-cascader>-->
          <!--&lt;!&ndash;<el-input v-model="form.cityName" placeholder="请输入城市名称" />&ndash;&gt;-->
        <!--</el-form-item>-->
        <el-form-item label="选择">
          <el-select v-model="form.cityName" placeholder="选择" clearable size="small">
            <el-option
              v-for="item in provinceList"
              :key="item.value"
              :label="item.value"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <!--<el-form-item label="城市选择">-->
          <!--<el-select v-model="form.cityName" placeholder="选择城市" clearable size="small">-->
            <!--<el-option-->
              <!--v-for="item in List"-->
              <!--:key="item.value"-->
              <!--:label="item.value"-->
              <!--:value="item.value"-->
            <!--/>-->
          <!--</el-select>-->
        <!--</el-form-item>-->
        <el-form-item label="状态选择">
          <el-select v-model="form.status" placeholder="选择状态" clearable size="small">
            <el-option
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <!--<el-form-item label="父级id" prop="parentCityId">-->
        <!--<el-input v-model="form.parentCityId" placeholder="请输入父级id" />-->
        <!--</el-form-item>-->
        <!--<el-form-item label="" prop="level">-->
        <!--<el-input v-model="form.level" placeholder="请输入" />-->
        <!--</el-form-item>-->
        <!--<el-form-item>-->
        <!--<el-form-item label="">-->
        <!--<el-radio-group v-model="form.status">-->
        <!--<el-radio label="1">请选择字典生成</el-radio>-->
        <!--</el-radio-group>-->
        <!--</el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="title" :visible.sync="open1" width="500px">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="分类权限">
          <el-tree
            :data="menuOptions"
            show-checkbox
            ref="menu"
            node-key="typeId"
            empty-text="加载中，请稍后"
            :props="defaultProps"
            :default-checked-keys='arr'
          ></el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCity, getCity, getType, gettypelist, delCity,updateCityService,addCity, updateCity, exportCity } from "@/api/system/city";
import { provinceAndCityData, regionData, provinceAndCityDataPlus, regionDataPlus, CodeToText, TextToCode } from 'element-china-area-data'
import {roleMenuTreeselect ,getTreeselect} from "@/api/system/menu";
import { roleDeptTreeselect } from "@/api/system/dept";
export default {
  name: "City",
  data() {
    return {

      arr:[],
      options: regionDataPlus,
      selectCity:[],
      provinceList:[],
      // 遮罩层
      city:"",
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      defaultProps: {
        children: "children",
        label: "typeName"
      },
      // 城市表格数据
      cityList: [],
      // 弹出层标题
      title: "",
      list:[],
      menuOptions: [],
      // 是否显示弹出层
      open: false,
      open1:false,
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        cityName: undefined,
        parentCityId: undefined,
        level: undefined,
        status: undefined,

      },
      // 表单参数
      form: {

      },
      // 表单校验
      rules: {

      }
    };
  },
  created() {
    this.getList();
    this.getDicts("sys_normal_disable").then(response => {
      this.statusOptions = response.data;
    });
  },
  watch: {
    dialogVisible (val) {
      if (val) {
        this.setDefaultChecked()  // 如果为true。那么调用设置树形默认值的方法
      }
    }
  },
  methods: {
    /** 查询城市列表 */
    handleChange (value) {
      console.log(CodeToText[this.selectCity[0]] + CodeToText[this.selectCity[1]])
    },
    getList() {
      for (var i = 0;i<this.options.length;i++)
      {
        this.provinceList[i] = {
          value:this.options[i].label
        }
      }

      this.loading = true;
      listCity(this.queryParams).then(response => {
        this.cityList = response.rows;
        this.total = response.total;
        this.loading = false;
      });

    },
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.open1 = false;
      this.reset();
    },

    // 表单重置
    reset() {
      this.selectCity = [],
      this.form = {
        cityId: undefined,
        cityName: undefined,
        parentCityId: undefined,
        level: undefined,
        status: "0",
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        typeIds:[],

      };
      this.resetForm("form");
    },
    handleAdd1(row){
      console.log(row)
      this.provinceList=[];

      for (var i = 0;i<this.options.length;i++)
      {
          if (this.options[i].label == row.cityName ){
            // console.log(this.options[i].children[1].label)
                for (var j =0;j<this.options[i].children.length; j++)
                this.provinceList[j] = {
                 value: this.options[i].children[j].label
                }

          }
      }
      this.reset();
      this.open = true;
      this.form.parentCityId = row.cityId
      this.title = "添加城市";
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    //多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.cityId)
      this.single = selection.length!=1
      this.multiple = !selection.length

    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getList();
      this.open = true;
      this.title = "添加省份";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.provinceList=[];

      for (var i = 0;i<this.options.length;i++)
      {     if(this.options[i].children){
              for (var  k= 0;k<this.options[i].children.length;k++) {
                if(this.options[i].children[k].label== row.cityName){
                  for (var j =0;j<this.options[i].children.length; j++)
                    this.provinceList[j] = {
                      value: this.options[i].children[j].label
                    }

                }
              }
      }


      }
      getCity(row.cityId).then(response => {
        this.form = response.data.data;
        this.open = true;
        this.title = "修改城市";
      });
    },

    /** 根据角色ID查询菜单树结构 */
    getRoleMenuTreeselect(cityId) {
        getType(cityId).then(response => {
        this.getMenuTreeselect()
        // console.log(response.data)

          for (var i = 0 ;i<response.data.length;i++)
            this.arr[i] =  response.data[i].typeId
            // console.log(arr)
        this.$refs.menu.setCheckedKeys(this.arr);
      });
    },

    /** 查询菜单树结构 */
    getMenuTreeselect() {
      gettypelist().then(response => {
        this.menuOptions = response.data;
        // console.log(this.menuOptions)
      });
    },
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.menu.getHalfCheckedKeys();

      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.menu.getCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
      console.log(checkedKeys)
    },
    /** 拿到表 */
    handleGet(row) {
      this.reset();
      this.city = row.cityId || this.ids
      this.$nextTick(() => {
        this.getRoleMenuTreeselect(row.cityId);
      });
      this.open1 = true;
      this.title = "关联分类";
    },
    /** 提交按钮 */
    submitForm: function() {
      // this.form.cityName = CodeToText[this.selectCity[0]]
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.cityId != undefined) {
            updateCity(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          } else {
            addCity(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          }
        }
      });
    },
    submit:function(){
      this.form.cityId = this.city
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.cityId != undefined) {
            this.form.typeIds = this.getMenuAllCheckedKeys();
            updateCityService(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open1 = false;
              } else {
                this.msgError(response.msg);
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const name = row.cityName||this.ids;
      const cityIds = row.cityId || this.ids;
      this.$confirm('是否确认删除城市名称:' + name + '的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delCity(cityIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    // handleExport() {
    //   const queryParams = this.queryParams;
    //   this.$confirm('是否确认导出所有城市数据项?', "警告", {
    //       confirmButtonText: "确定",
    //       cancelButtonText: "取消",
    //       type: "warning"
    //     }).then(function() {
    //       return exportCity(queryParams);
    //     }).then(response => {
    //       this.download(response.msg);
    //     }).catch(function() {});
    // }
  }
};
</script>
